//
//  ScrollerViewController.m
//  Camera
//
//  Created by gml on 2018/10/31.
//  Copyright © 2018年 gml. All rights reserved.
//

#import "GMLHomeViewController.h"
#import "FirstViewController.h"
#import "SecondViewController.h"
#import "GMLPopArrowMenuController.h"

#import "GMLHomeHeaderView.h"
#import "SPPageMenu.h"
#import "GMLGradientNaviView.h"

#define kPageMenuH  60
#define kNaviH  (SAFE_SCREEN_BOTTOM>0.0 ? (SAFE_SCREEN_TOP+44) : 64)
@interface GMLHomeViewController ()<SPPageMenuDelegate,UIScrollViewDelegate,BasePopMenuControllerDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) GMLHomeHeaderView *headerView;
@property (nonatomic, strong) SPPageMenu *pageMenu;
@property (nonatomic,strong) GMLGradientNaviView *naviView;
@property (nonatomic, assign) CGFloat lastPageMenuY;
@property (nonatomic, assign) CGPoint lastPoint;

@end

@implementation GMLHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    [self addSubViews];
    
}
- (void)addSubViews
{
    self.lastPageMenuY = kHeaderViewH;
    
    // 添加一个全屏的scrollView
    [self.view addSubview:self.scrollView];

    // 添加头部视图
    [self.view addSubview:self.headerView];
    
    // 添加分页菜单
    [self.view addSubview:self.pageMenu];
    
    // 添加导航view
    [self.view addSubview:self.naviView];
    
    // 添加4个子控制器SecondViewController
    [self addChildViewController:[[FirstViewController alloc] init]];
    [self addChildViewController:[[SecondViewController alloc] init]];
    
    // 先将第一个子控制的view添加到scrollView上去
    [self.scrollView addSubview:self.childViewControllers[0].view];
    
    // 监听子控制器发出的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subScrollViewDidScroll:) name:ChildScrollViewDidScrollNSNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshState:) name:ChildScrollViewRefreshStateNSNotification object:nil];
    
}
#pragma mark -- noti 通知
// 子控制器上的scrollView已经滑动的代理方法所发出的通知(核心)
- (void)subScrollViewDidScroll:(NSNotification *)noti {
    
    // 取出当前正在滑动的tableView
    UIScrollView *scrollingScrollView = noti.userInfo[@"scrollingScrollView"];
    CGFloat offsetDifference = [noti.userInfo[@"offsetDifference"] floatValue];
    
    CGFloat distanceY;
    
    // 取出的scrollingScrollView并非是唯一的，当有多个子控制器上的scrollView同时滑动时都会发出通知来到这个方法，所以要过滤
    BaseTableViewController *baseVc = self.childViewControllers[self.pageMenu.selectedItemIndex];
    
    if (scrollingScrollView == baseVc.tableView && baseVc.isFirstViewLoaded == NO) {
        
        // 让分页菜单跟随scrollView滑动
        CGRect pageMenuFrame = self.pageMenu.frame;
        
        if (pageMenuFrame.origin.y >= kNaviH) {
            // 往上移
            if (offsetDifference > 0 && scrollingScrollView.contentOffset.y+kScrollViewBeginTopInset > 0) {
                
                if (((scrollingScrollView.contentOffset.y+kScrollViewBeginTopInset+self.pageMenu.frame.origin.y)>=kHeaderViewH) || scrollingScrollView.contentOffset.y+kScrollViewBeginTopInset < 0) {
                    // 分页菜单的y值等于当前正在滑动且显示在屏幕范围内的的scrollView的contentOffset.y的改变量(这是最难的点)
                    pageMenuFrame.origin.y += -offsetDifference;
                    if (pageMenuFrame.origin.y <= kNaviH) {
                        pageMenuFrame.origin.y = kNaviH;
                    }
                }
            } else { // 往下移
                if ((scrollingScrollView.contentOffset.y+kScrollViewBeginTopInset+self.pageMenu.frame.origin.y)<kHeaderViewH) {
                    pageMenuFrame.origin.y = -scrollingScrollView.contentOffset.y-kScrollViewBeginTopInset+kHeaderViewH;
                    if (pageMenuFrame.origin.y >= kHeaderViewH) {
                        pageMenuFrame.origin.y = kHeaderViewH;
                    }
                }
            }
        }
        self.pageMenu.frame = pageMenuFrame;
        
        CGRect headerFrame = self.headerView.frame;
        headerFrame.origin.y = self.pageMenu.frame.origin.y-kHeaderViewH;
        self.headerView.frame = headerFrame;
        
        // 记录分页菜单的y值改变量
        distanceY = pageMenuFrame.origin.y - self.lastPageMenuY;
        self.lastPageMenuY = self.pageMenu.frame.origin.y;
        
        // 让其余控制器的scrollView跟随当前正在滑动的scrollView滑动
        [self followScrollingScrollView:scrollingScrollView distanceY:distanceY];
        
        [self changeColorWithOffsetY:-self.pageMenu.frame.origin.y+kHeaderViewH];
    }
    baseVc.isFirstViewLoaded = NO;
}
- (void)refreshState:(NSNotification *)noti {
    BOOL state = [noti.userInfo[@"isRefreshing"] boolValue];
    // 正在刷新时禁止self.scrollView滑动
    self.scrollView.scrollEnabled = !state;
}

#pragma mark -- action
- (void)followScrollingScrollView:(UIScrollView *)scrollingScrollView distanceY:(CGFloat)distanceY{
    BaseTableViewController *baseVc = nil;
    for (int i = 0; i < self.childViewControllers.count; i++) {
        baseVc = self.childViewControllers[i];
        if (baseVc.tableView == scrollingScrollView) {
            continue;
        } else {
            CGPoint contentOffSet = baseVc.tableView.contentOffset;
            contentOffSet.y += -distanceY;
            baseVc.tableView.contentOffset = contentOffSet;
        }
    }
}

- (void)changeColorWithOffsetY:(CGFloat)offsetY {
    // 滑出20偏移时开始发生渐变,(kHeaderViewH - 20 - 64)决定渐变时间长度
    NSLog(@"------------%f",offsetY);
    if (offsetY >= 0) {
        CGFloat alpha = (offsetY)/(kHeaderViewH-kNaviH);
        // 该属性是设置导航栏背景渐变
        self.naviView.navAlpha = alpha;
    } else {
        self.naviView.navAlpha = 0;
        
    }

    self.headerView.contentOffsetY = offsetY;
}



#pragma mark --scrollerView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    BaseTableViewController *baseVc = self.childViewControllers[self.pageMenu.selectedItemIndex];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (baseVc.tableView.contentSize.height < kMainBoundsHeight && [baseVc isViewLoaded]) {
            [baseVc.tableView setContentOffset:CGPointMake(0, -kScrollViewBeginTopInset) animated:YES];
        }
    });
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    BaseTableViewController *baseVc = self.childViewControllers[self.pageMenu.selectedItemIndex];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (baseVc.tableView.contentSize.height < kMainBoundsHeight && [baseVc isViewLoaded]) {
            [baseVc.tableView setContentOffset:CGPointMake(0, -kScrollViewBeginTopInset) animated:YES];
        }
    });
}

#pragma mark - SPPageMenuDelegate
- (void)pageMenu:(SPPageMenu *)pageMenu itemSelectedFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    if (!self.childViewControllers.count) { return;}
    // 如果上一次点击的button下标与当前点击的buton下标之差大于等于2,说明跨界面移动了,此时不动画.
    if (labs(toIndex - fromIndex) >= 2) {
        [self.scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width * toIndex, 0) animated:NO];
    } else {
        [self.scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width * toIndex, 0) animated:YES];
    }
    
    BaseTableViewController *targetViewController = self.childViewControllers[toIndex];
    // 如果已经加载过，就不再加载
    if ([targetViewController isViewLoaded]) return;
    
    // 来到这里必然是第一次加载控制器的view，这个属性是为了防止下面的偏移量的改变导致走scrollViewDidScroll
    targetViewController.isFirstViewLoaded = YES;
    
    targetViewController.view.frame = CGRectMake(kMainBoundsWidth*toIndex, 0, kMainBoundsWidth, kMainBoundsHeight);
    UIScrollView *s = targetViewController.tableView;
    CGPoint contentOffset = s.contentOffset;
    contentOffset.y = -self.headerView.frame.origin.y-kScrollViewBeginTopInset;
    if (contentOffset.y + kScrollViewBeginTopInset >= kHeaderViewH) {
        contentOffset.y = kHeaderViewH-kScrollViewBeginTopInset;
    }
    s.contentOffset = contentOffset;
    [self.scrollView addSubview:targetViewController.view];
}
/*
- (void)panGestureRecognizerAction:(UIPanGestureRecognizer *)pan {
    if (pan.state == UIGestureRecognizerStateBegan) {
        
    } else if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint currenrPoint = [pan translationInView:pan.view];
        CGFloat distanceY = currenrPoint.y - self.lastPoint.y;
        self.lastPoint = currenrPoint;
        
        BaseTableViewController *baseVc = self.childViewControllers[self.pageMenu.selectedItemIndex];
        CGPoint offset = baseVc.scrollView.contentOffset;
        offset.y += -distanceY;
        if (offset.y <= -kScrollViewBeginTopInset) {
            offset.y = -kScrollViewBeginTopInset;
        }
        baseVc.scrollView.contentOffset = offset;
    } else {
        [pan setTranslation:CGPointZero inView:pan.view];
        self.lastPoint = CGPointZero;
    }
    
}
*/

- (void)popMenuView:(UIView *)senderView
{
    GMLPopArrowMenuController *menuView = [[GMLPopArrowMenuController alloc] initDefaultArrowheadMenuWithTitle:@[@"联系客服"] icon:@[@"pop_menu_contact_icon"] menuPlacements:GMLMenuPlacements_Bottom];
    menuView.delegate = self;
    [menuView presentMenuView:senderView];
}

#pragma mark -- BasePopMenuControllerDelegate 弹出菜单view
- (void)menu:(BasePopMenuController *)menu didClickedItemUnitWithTag:(NSInteger)tag andItemUnitTitle:(NSString *)title
{
    
}

#pragma -- lazy
-(GMLHomeHeaderView *)headerView
{
    if (_headerView == nil) {
        _headerView = [[GMLHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, kMainBoundsWidth, kHeaderViewH)];
        
    }
    return _headerView;
}


- (UIScrollView *)scrollView {
    
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, 0, kMainBoundsWidth, kMainBoundsHeight-SAFE_SCREEN_BOTTOM);
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.contentSize = CGSizeMake(kMainBoundsWidth*2, 0);
        _scrollView.backgroundColor = [UIColor colorWithWhite:1 alpha:0];
        if (@available(iOS 11.0, *)) {
            _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            
        }
    }
    return _scrollView;
}


- (SPPageMenu *)pageMenu {
    
    if (!_pageMenu) {
        _pageMenu = [SPPageMenu pageMenuWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerView.frame), kMainBoundsWidth, kPageMenuH) trackerStyle:SPPageMenuTrackerStyleYouCabBottomTitle];
        [_pageMenu setItems:@[@"实时任务",@"选单任务"] selectedItemIndex:0];
        _pageMenu.delegate = self;
        _pageMenu.selectedItemTitleFont = [UIFont fontWithName:@"PingFangSC-Semibold" size:19];
        _pageMenu.unSelectedItemTitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        _pageMenu.selectedItemTitleColor = [UIColor blackColor];
        _pageMenu.unSelectedItemTitleColor = [UIColor colorWithWhite:0 alpha:1];
        _pageMenu.tracker.backgroundColor =UIColorFromRGB(0xE2452A);
        _pageMenu.selectedItemZoomScale = 1.2;
        _pageMenu.permutationWay = SPPageMenuPermutationWayNotScrollEqualWidths;
        _pageMenu.bridgeScrollView = self.scrollView;
        _pageMenu.trackerWidth = 80;
        [_pageMenu setTrackerHeight:5 cornerRadius:0];
        [_pageMenu setBackgroundImage:[UIImage imageNamed:@"tab_bg"] barMetrics:UIBarMetricsDefaultPrompt];
        CALayer *line = [CALayer layer];
        line.frame = CGRectMake(15, _pageMenu.bounds.size.height - 1, _pageMenu.bounds.size.width - 30, 0.5);
        line.backgroundColor = UIColorFromRGB(0xDCDCDC).CGColor;
        //        line.backgroundColor = [UIColor blueColor];
        [_pageMenu.layer addSublayer:line];
    }
    return _pageMenu;
}
- (GMLGradientNaviView *)naviView
{
    if (_naviView == nil) {
        CGFloat height = SAFE_SCREEN_BOTTOM > 0.0 ? (44.0+SAFE_SCREEN_TOP):64;
        _naviView = [[GMLGradientNaviView alloc] initWithFrame:CGRectMake(0, 0, kMainBoundsWidth, height)];
        _naviView.navAlpha = 0.0f;
        WS(weakSelf);
        _naviView.leftBlcok = ^(UIButton *left){
            
        };
        _naviView.rightBlcok = ^(UIButton *right){
            [weakSelf popMenuView:right];
        };
    }
    return _naviView;
}
@end
